<template>
  <div class="Terminal_box" ref="boxTheSize">
    <el-row>
      <el-col :span="24">
        <div class="grid-content bg-purple-light">
          <div class="tltle_box">
            <div class="tltle_box_l">
              <div class="Material_r">
                <el-input placeholder="请输入关键字" v-model="inputText" @clear="seekTableList(1)" clearable></el-input>
                <el-button type="primary" icon="el-icon-search" @click="seekTableList">搜索</el-button>
              </div>
            </div>
            <div class="tltle_box_r">
              <!-- <el-tooltip class="item" effect="dark" content="创建角色" placement="top"> -->
                <el-button @click="OpenRoleCompile" v-if="Invoking.forFunctionCode('roles:insert')">
                  <img src="../../assets/images/user9_03.png" alt />
                  <div>创建角色</div>
                </el-button>
              <!-- </el-tooltip> -->
            </div>
          </div>
          <div class="Terminal_table">
             <zycm-table
              @zyLoadData="loadData"
              zy-table-ref="media_group_oleUser_table"
              :zy-table-data="tabledataList"
              zy-table-height="63vh"
            >
              <el-table-column label="角色名称" prop="roleName" width="150" show-overflow-tooltip></el-table-column>
              <el-table-column label="角色说明" prop="roleIntroduce" min-width="120" show-overflow-tooltip></el-table-column>
              <el-table-column label="创建时间" prop="roleCreateTime" width="140" show-overflow-tooltip>
                <template slot-scope="scope">
                  <div>{{scope.row.roleCreateTime | dateFormat}}</div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template slot-scope="scope" fixed="right"  width="140" >
                  <el-dropdown :size="GlobalVar.sizeSet.dropdown" type="primary" v-if="Invoking.ifFunctionCode('roles:updateByPrimaryKey#rolesFunction:savePrivilege#roles:deleteByPrimaryKey')">
                    <el-button type="primary" :size="GlobalVar.sizeSet.btn">
                      更多
                      <i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item @click.native="compileRole(scope.row)" v-if="Invoking.forFunctionCode('roles:updateByPrimaryKey')">编辑角色</el-dropdown-item>
                      <el-dropdown-item @click.native="CheckTheData(scope.row)" v-if="Invoking.forFunctionCode('rolesFunction:savePrivilege')">权限设置</el-dropdown-item>
                      <el-dropdown-item @click.native="removeRole(scope.row)" v-if="Invoking.forFunctionCode('roles:deleteByPrimaryKey')">删除角色</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>
              </el-table-column>
             </zycm-table>

          </div>
        </div>
      </el-col>
    </el-row>
    <!-- 系统公告 -->
    <el-dialog
      :title="!presentTableData.roleName?'创建角色':presentTableData.roleName+'--编辑角色'"
      :visible.sync="roleCompile"
     :width="this.$store.getters.offsetWidth"
      @close="closeRoleCompile"
      v-dialogDrag
      ref="dialog__wrapper"
      :close-on-click-modal="false"
    >
      <div class="dialog-body">
        <div class="line">
          <div>
            <el-form :rules="rules" ref="ruleForm" :model="roleForm" label-width="100px">
              <el-form-item label="角色名称" prop="roleName">
                <el-input
                  placeholder="请输入角色名称"
                  v-model="roleForm.roleName"
                  @input="blurRoleName(roleForm.roleName)"
                ></el-input>
              </el-form-item>
              <el-form-item label="角色说明" class="auditOpinion" prop="roleIntroduce">
                <el-input
                  type="textarea"
                  maxlength="200"
                  placeholder="输入内容200字内"
                  v-model="roleForm.roleIntroduce"
                ></el-input>
              </el-form-item>
            </el-form>
          </div>
          <span
            style="width: 100%;text-align: center;margin: 20px auto 0;height: 50px;display: block;"
            class="button_dialog"
          >
            <el-button style="background-color:#4d9ce0;color:#fff" @click="saveRoleCompile">确 定</el-button>
            <el-button @click="cancelCompile">清 空</el-button>
          </span>
        </div>
      </div>
    </el-dialog>
    <!-- 配置权限 -->
    <rolecheckd v-bind:Configure="Configure" ref="ConfigureRef" v-bind:roleId="roleId"></rolecheckd>
  </div>
</template>

<script>
import rolecheckd from "../../components/templateTable/rolecheckd.vue";
export default {
  components: {
    rolecheckd,
  },
  data() {
    return {
      query: {
        page: 1,
        pageSize: this.GlobalVar.query.pageSize,
        total: 0,
      },
      roleCompile: false,
      Configure: false,
      // 搜索字段
      inputText: "",
      TerminalHeight: "",
      tableData: [],
      roleForm: {
        roleName: "",
        roleIntroduce: "",
      },
      roleId: "",
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleIntroduce: [
          { required: true, message: "请输入角色说明", trigger: "blur" },
        ],
      },
      checkedAllText: "",
      presentTableData: "",
      thisFormData: new FormData(),
      tabledataList: [], //保存当页的所有table数据
      tablePageList: [], //保存对应table的page数据
      NameRepetition:false
    };
  },

  created() {
    this.clientHeight();
    this.currentTableLoad("media_group_oleUser_table", true);
    this.tableList();
  },

  methods: {
                //给子组件刷新用
    async loadData(formData, tableRef) {
      //提前修正isReqData状态 后续赋值随时会触发table组件的computed  后面还要进行一次修正
      for (let key in this.tabledataList) {
        if (this.tabledataList[key].ref === tableRef) {
          this.tabledataList[key].isReqData = true; //标记更新数据的状态 组件中会根据此判断是否重新更新数据
        } else {
          this.tabledataList[key].isReqData = false;
        }
      }

      //子组件触发查询时  处理查询的参数
      if (this.tablePageList[tableRef]) {
        this.tablePageList[tableRef].set("page", formData.get("page"));
        this.tablePageList[tableRef].set("pageSize", formData.get("pageSize"));
      }

      let res;
      if (tableRef == "media_group_oleUser_table") {
        //发布-选择节目列表
        res = await this.$http.post(
          "roles/selectPage",
          this.tablePageList[tableRef]
        );
        // this.ProgramSelectList = [];
      }

      if (res && res.data.result === "success") {
        //记录更新分页数据
        res.data.ref = tableRef;
        //更新记录
        let sign = 0;
        for (let key in this.tabledataList) {
          if (this.tabledataList[key].ref === tableRef) {
            if (sign > 1) {
              //去掉重复数据
              this.tabledataList.splice(key, 1);
            } else {
              this.tabledataList.splice(key, 1, res.data);
              this.tabledataList[key].isReqData = true; //标记更新数据的状态 组件中会根据此判断是否重新更新数据
            }
            sign++;
          } else {
            this.tabledataList[key].isReqData = false;
          }
        }
        if (sign == 0) {
          //没有初始化时
          res.data.isReqData = true;
          this.tabledataList.push(res.data);
        }
      } else {
        if (res && res.data.result === "error") {
          this.$message({
            type: "error",
            message: res.data.message,
          });
        } else {
          this.$message({
            type: "error",
            message: "请求数据出现异常",
          });
        }
      }
    },
    //当页刷新数据
    currentTableLoad(tableRef, firstPage, fd) {
      if (firstPage) {
        //加载第一页数据
        if (!this.tablePageList[tableRef]) {
          this.tablePageList[tableRef] = new FormData();
          this.tablePageList[tableRef].set("pageSize", this.GlobalVar.query.pageSize);
        }
        this.tablePageList[tableRef].set("page", 1);
      }
      //如果有其他查询参数 合并处理
      if (fd) {
        for (let item of fd.entries()) {
          this.tablePageList[tableRef].set(item[0], item[1]);
        }
      }
      this.loadData(this.tablePageList[tableRef], tableRef);
    },

    OpenRoleCompile() {
      this.roleForm={
        roleName : "",
        roleIntroduce : "",
      }
            if( this.$refs.ruleForm){
     this.$refs.ruleForm.resetFields();
      }
      this.roleCompile = true;
      this.flag = false;
      this.presentTableData = "";
    },
 
    async tableList() {
      // let formData = new FormData();
      let token = window.sessionStorage.getItem("token");
      this.thisFormData.set("zycmToken", token);
      this.thisFormData.set("page", this.query.page);
     this.thisFormData.set("pageSize", this.query.pageSize);
   
      const { data: res } = await this.$http.post("roles/selectPage", this.thisFormData);
      this.query.page = res.page == "undefined" ? 1 : res.page;
      this.query.pageSize = res.pageSize == "undefined" ? this.GlobalVar.query.pageSize : res.pageSize;
      this.query.total = res.total;
      this.tableData = res.dataList;
    },
    seekTableList(e) {
      // this.query.page = 1;
      // this.query.pageSize = 10;
      //   this.thisFormData.set("roleName", this.inputText);
      // this.tableList();
          let fd = new FormData();
      //终端列表查询
      if (e == 1) {
        fd.set("roleName", "");
        this.currentTableLoad("media_group_oleUser_table", true, fd);
      } else {
       fd.set("roleName", this.inputText);
        this.currentTableLoad("media_group_oleUser_table", true, fd);
      }
    },
    // 获取权限勾选数据
    CheckTheData(e) {
      this.roleId = e;
      this.$refs.ConfigureRef.openRole(e);
      this.Configure = !this.Configure;
    },
    // 点击保存角色
    saveRoleCompile() {
      let url = "";
      let ftpId = "";
      if (this.flag) {
        url = "roles/updateByPrimaryKey";
      } else {
        url = "roles/insert";
      }
      if(this.NameRepetition){
         this.$message({
          type: "warning",
          message: "此角色名已被占用",
        });
        return
      }
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let formData = new FormData();
          let token = window.sessionStorage.getItem("token");
          formData.append("zycmToken", token);
          formData.append("roleName", this.roleForm.roleName);
          formData.append("roleIntroduce", this.roleForm.roleIntroduce);
          formData.append(
            "roleId",
            this.roleForm.roleId ? this.roleForm.roleId : ""
          );
          const { data: res } = await this.$http.post(url, formData);
          if (res.result == "success") {
            this.$message({
              type: "success",
              message: res.message,
            });
          } else {
            this.$message({
              type: "error",
              message: res.message,
            });
          }
          this.roleCompile = false;
          this.seekTableList();
        } else {
          return false;
        }
      });
    },
    // 取消清空
    cancelCompile() {
      this.roleForm.roleName = "";
      this.roleForm.roleIntroduce = "";
    },
    // 编辑角色
    async compileRole(e, t) {
      if(this.$refs.ruleForm){
         this.$refs.ruleForm.resetFields();
      }
      this.presentTableData = e;
      let formData = new FormData();
      let token = window.sessionStorage.getItem("token");
      formData.append("zycmToken", token);
      formData.append("roleId", e.roleId);
      const { data: res } = await this.$http.post(
        "roles/selectByPrimaryKey",
        formData
      );
      this.roleForm = res.data;
      this.flag = true;
      this.roleCompile = true;
       this.currentTableLoad("media_group_oleUser_table");
    },
    // 删除角色
    removeRole(e) {
      this.$confirm("此操作将删除" + e.roleName + ",是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let formData = new FormData();
          let token = window.sessionStorage.getItem("token");
          formData.append("zycmToken", token);
          formData.append("roleId", e.roleId);
          const { data: res } = await this.$http.post(
            "roles/deleteByPrimaryKey",
            formData
          );
          if (res.result == "success") {
            this.$message({
              type: "success",
              message: res.message,
            });
          } else {
            this.$message({
              type: "error",
              message: res.message,
            });
          }
              this.query.page=1
          this.query.pageSize=this.GlobalVar.query.pageSize
          this.seekTableList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 关闭弹框
    closeRoleCompile() {
      this.roleForm={
        roleName : "",
        roleIntroduce : "",
      }
      // this.roleForm.roleIntroduce = "";
      this.roleForm.roleId = "";
      // this.$refs.ruleForm.resetFields();
    },
    // 判断角色名是否占用
    async blurRoleName(e) {
      let formData = new FormData();
      let token = window.sessionStorage.getItem("token");
      formData.append("zycmToken", token);
      formData.append("roleName", e);
      if (this.roleForm.roleId) {
        formData.append("roleId", this.roleForm.roleId);
      }
      const { data: res } = await this.$http.post(
        "roles/selectByName",
        formData
      );
       if (!res.data) {
         this.NameRepetition=true
         return
      }else if (res.data.length>0) {
         this.NameRepetition=true
         return
      }
      this.NameRepetition=false
      // this.saveRoleCompile()
    },
    clientHeight() {
      this.$nextTick(() => {
        this.TerminalHeight = this.$refs.boxTheSize.clientHeight - 95;
      });
    },

  },
};
</script>



<style lang="stylus" scoped>
.Terminal_box {
  overflow hidden
  .auditOpinion {
    /deep/.el-form-item__label {
      line-height: 80px;
    }
    /deep/.el-form-item__label,
    /deep/.el-textarea__inner {
      height: 80px;
    }
  }
  .BgColor {
    background-color: #e4f2ff;
    height: 100%;
  }
  /deep/.has-gutter .el-checkbox {
    display: none;
  }
  .tltle_box {
    margin: 1.5% 0;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    height: 100px;
    width: 100%;
    align-items: center;
    margin-bottom: 15px;
    border-radius: 5px;
    .tltle_box_l {
      display: flex;
      .Material_r {
        display: flex;
        margin-left: 20px;
        /deep/.el-button {
          margin: 0 0 0 20px;
          height: 40px;
          background-color: #2183d8;
        }
        .refresh {
          background-color: #fff;
          color: #2183d8;
        }
      }
    }
    .tltle_box_r {
      padding-right: 20px;
      .el-button {
        float: right;
        background-color: #f2faff;
        min-width: 50px;
        height: 50px;
        border: none;
        margin-left: 0;
        margin: 0 5px;
        padding: 0 5px;
        border-radius: 5px;
        font-size:12px;
        img {
          width: 26px;
          height: 26px;
        }
      }
      /deep/.el-button:hover {
        background-color: #f2f2f2;
      }
    }
    /deep/.el-table th,
    .el-table tr {
      background-color: #fafafa;
    }
  }
  .Terminal_table {
    margin: 1.5% 0;
    width: 100%;
    background-color: #fff;
    border: 0.1px solid #fff;
    .el-table {
      margin: 1.5%;
      width: 97%;
      // padding: 20px;
      margin: 20px;
    }
  }
  .Terminal_tree {
    padding: 20px;
  }
  /deep/.el-tree {
    background-color: #e4f2ff;
  }
  .pagination {
    display: flex;
    height: 60px;
    justify-content: center;
  }
  /deep/.el-pager li,
  /deep/.el-pagination .btn-next,
  /deep/ .el-pagination .btn-prev {
    border: 1px solid #eee;
    border-radius: 5px;
    margin: 0 5px;
    color: #333;
    padding: 0;
  }
  /deep/.el-pager li.active {
    background-color: #2183d8;
    color: #fff;
  }
  /deep/.el-pagination__sizes {
    padding-left: 20px;
  }
  .fold {
    display: flex;
    width: 100%;
  }
  .fold /deep/.el-form-item__label {
    color: #0095fb;
  }
  .fold /deep/.el-form-item {
    width: 25%;
  }
  /deep/.el-tabs--bottom /deep/.el-tabs__item.is-bottom:nth-child(2),
  /deep/.el-tabs--bottom .el-tabs__item.is-top:nth-child(2),
  /deep/.el-tabs--top .el-tabs__item.is-bottom:nth-child(2),
  /deep/.el-tabs--top .el-tabs__item.is-top:nth-child(2) {
    padding-left: 20px;
  }
  /deep/.el-tabs__item {
    padding: 0 20px;
  }
  /deep/.el-tabs__active-bar {
    padding: 0 20px;
    left: -20px;
    color: #2183d8;
  }
  /deep/.el-table th,
  .el-table tr {
    background-color: #fafafa;
  }
}
/deep/.el-dialog {
  .checkboxDialog {
    margin-bottom: 20px;
  }
  .first_box {
    height: 250px;
    width: 99%;
    border: 1px solid #eee;
  }
  .auditOpinion {
    /deep/.el-form-item__label {
      line-height: 120px;
    }
    /deep/.el-form-item__label,
    /deep/.el-textarea__inner {
      height: 120px;
    }
  }

  /deep/.el-tree {
    background-color: #fff;
    padding: 0 0 5% 10%;
  }
  .selectTerminal {
    /deep/.el-tree {
      background-color: #fff;
      padding: 0 0 5% 10%;
    }
  }
  /deep/.el-select {
    display: block;
  }
  /deep/.el-dialog__header {
    background-color: #efefef;
    padding: 0;
    line-height: 50px;
    padding-left: 20px;
    color: #333;
    font-size: 16px;
  }
  /deep/.el-form-item__label {
    background-color: #efefef;
    border-radius: 0;
    height: 40px;
    border: 1px solid #dcdfe6;
    border-right: none;
    box-sizing: border-box;
    text-align: center;
    padding-left: 10px;
  }
  /deep/.el-input__inner,
  /deep/.el-textarea__inner {
    border-radius: 0;
  }
  /deep/.el-button {
    padding: 12px 25px;
  }
  .opinion {
    /deep/.el-form-item__label {
      height: 80px;
      line-height: 80px;
    }
  }
}
</style>
